package com.cherish.pattern.singleton.register;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Classname ContainerSingleton
 * @Date 2019/3/11 23:34
 * @Author admin
 * @Description 容器式 单例模式
 * Spring中的做法
 */
public class ContainerSingleton {

    //第一步  构造函数私有化
    private ContainerSingleton() {
    }

    private static Map<String, Object> ioc = new ConcurrentHashMap<>();

    public static ContainerSingleton getInstance(String className) {
        synchronized (ioc) {
            if (!ioc.containsKey(className)) {
                Object obj = null;
                try {
                    obj = Class.forName(className).newInstance();
                    ioc.put(className, obj);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return (ContainerSingleton) obj;
            } else {
                return (ContainerSingleton) ioc.get(className);
            }
        }
    }


}
